package cn.yunhe.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;




@Controller
public class HelloController {
    /**
     * 测试
     * @return
     */
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        System.out.println("hello");
        return "ok";
    }
    /**
     * 测试thymeleaf
     */
    @RequestMapping("testThymeleaf")
    public String testThymeleaf(Model model){
        model.addAttribute("msg","用户操作界面");
        return "test";
    }

    @RequestMapping("add")
    public String toAdd(){
        return "/user/add";
    }

    @RequestMapping("update")
    public String toUpdate(){
        return "/user/update";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
        return "/user/login";
    }

    @RequestMapping("unAuth")
    public String unAuth(){
        return "unAuth";
    }


    @RequestMapping("/login")
    public String Login(String name,String password,Model model){
        /**
         * 使用Shiro编写认证操作
         */
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(name,password);
        //3.执行登录方法
        try {
            subject.login(token);
            //登录成功
            //跳转到test.html
            return "redirect:/testThymeleaf";
        }catch (UnknownAccountException e){
            /*e.printStackTrace();*/
            //登录失败：用户名不存在
            model.addAttribute("message","用户名不存在");
            return "/user/login";
        }catch (IncorrectCredentialsException e){
            /*e.printStackTrace();*/
            model.addAttribute("message","密码错误");
            return "/user/login";

        }
    }





}
